﻿using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Data;
using System.Net.Http.Headers;
using System.Net.Http;
using learun.util;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using Quartz.Impl;
using APICommond;
using NLog;

namespace Assets.API.Work
{
    public class WorkJob : IJob
    {
        internal Logger _logger = LogManager.GetCurrentClassLogger();
        public async Task Execute(IJobExecutionContext context)
        {
            try
            {
                _logger.Info("定时时间到");
                DataTable table = await BusinessRule.Warning.Waring.GetProject1();
                foreach (DataRow row in table.Rows)
                {
                    string projcode = Convert.ToString(row["projcode"]);
                    string functioncode = Convert.ToString(row["functioncode"]);
                    string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    string guiid = Guid.NewGuid().ToString();
                    using (var client = new HttpClient())
                    {
                        client.DefaultRequestHeaders.Accept.Clear();
                        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                        string body = "{\"appkey\":\"" + ConfigHelper.GetConfig().key + "\",\"projcode\":\"" + projcode + "\"}";
                        //string body = "{\"projcode\":\"" + procode + "\"}";
                        JObject j = JObject.Parse(body);
                        //转为链接需要的格式
                        HttpContent httpContent = new JsonContent(j);
                        //client.BaseAddress = new Uri(ConfigHelper.GetConfig().asset);
                        client.DefaultRequestHeaders.Add("appkey", ConfigHelper.GetConfig().key);
                        client.DefaultRequestHeaders.Add("time", time);
                        client.DefaultRequestHeaders.Add("guid", guiid);
                        client.DefaultRequestHeaders.Add("sign", APICommond.CreateHeader.ToMD5String(ConfigHelper.GetConfig().key + time + guiid + JsonConvert.SerializeObject(j) + ConfigHelper.GetConfig().secret));
                        string result = "";
                        switch (functioncode)
                        {
                            case "8"://项目立项
                                HttpResponseMessage response = client.PostAsync(ConfigHelper.GetConfig().asset + "projectpublish", httpContent).Result;
                                if (response.IsSuccessStatusCode)
                                {
                                    Task<string> t = response.Content.ReadAsStringAsync();
                                    if (t != null)
                                    {
                                        result = t.Result;
                                        _logger.Info(result);
                                        JObject j1 = JObject.Parse(t.Result);
                                        if (j1["status"].ToString() == "True")
                                        {
                                            string data = j1["data"].ToString();
                                            try
                                            {
                                                data = DES.DecryptDES(data, ConfigHelper.GetConfig().desKey);
                                            }
                                            catch (Exception e)
                                            {
                                                _logger.Info("回调接口projectpublish，解密失败");
                                            }
                                            JObject jb = JObject.Parse(data);
                                            await BusinessRule.Warning.Waring.SaveProject(jb);
                                            string err = await BusinessRule.Warning.Waring.InsertMessage(JsonConvert.SerializeObject(j), JsonConvert.SerializeObject(t.Result));
                                        }

                                    }
                                }
                                break;
                            case "6"://合同录入
                                HttpResponseMessage response1 = client.PostAsync(ConfigHelper.GetConfig().asset + "contractinformation", httpContent).Result;
                                if (response1.IsSuccessStatusCode)
                                {
                                    Task<string> t = response1.Content.ReadAsStringAsync();
                                    if (t != null)
                                    {
                                        result = t.Result;
                                        _logger.Info(result);
                                        JObject j1 = JObject.Parse(t.Result);
                                        if (j1["status"].ToString() == "True")
                                        {
                                            string data = j1["data"].ToString();
                                            try
                                            {
                                                data = DES.DecryptDES(data, ConfigHelper.GetConfig().desKey);
                                            }
                                            catch (Exception e)
                                            {
                                                _logger.Info("回调接口projectpublish，解密失败");
                                            }
                                            _logger.Debug("解密后：" + data);
                                            JObject jb = JObject.Parse(data);
                                            jb["projresult"] = 12;
                                            await BusinessRule.Warning.Waring.SaveProjectendresult(jb);

                                            string ver = await BusinessRule.Warning.Waring.InsertContract(jb);
                                            if (ver == "")
                                            {
                                                _logger.Debug("合同数据保存成功");
                                            }
                                            else
                                            { _logger.Debug("合同数据保存失败：" + ver); }
                                            string err = await BusinessRule.Warning.Waring.InsertMessage(JsonConvert.SerializeObject(j), JsonConvert.SerializeObject(t.Result));

                                        }

                                    }
                                }
                                break;
                            case "12"://合同录入
                                HttpResponseMessage response12 = client.PostAsync(ConfigHelper.GetConfig().asset + "contractinformation", httpContent).Result;
                                if (response12.IsSuccessStatusCode)
                                {
                                    Task<string> t = response12.Content.ReadAsStringAsync();
                                    if (t != null)
                                    {
                                        result = t.Result;
                                        _logger.Info(result);
                                        JObject j1 = JObject.Parse(t.Result);
                                        if (j1["status"].ToString() == "True")
                                        {
                                            string data = j1["data"].ToString();
                                            try
                                            {
                                                data = DES.DecryptDES(data, ConfigHelper.GetConfig().desKey);
                                            }
                                            catch (Exception e)
                                            {
                                                _logger.Info("回调接口projectpublish，解密失败");
                                            }
                                            _logger.Debug("解密后：" + data);
                                            JObject jb = JObject.Parse(data);
                                            jb["projresult"] = 12;
                                            await BusinessRule.Warning.Waring.SaveProjectendresult(jb);

                                            string ver = await BusinessRule.Warning.Waring.InsertContract(jb);
                                            if (ver == "")
                                            {
                                                _logger.Debug("合同数据保存成功");
                                            }
                                            else
                                            { _logger.Debug("合同数据保存失败：" + ver); }
                                            string err = await BusinessRule.Warning.Waring.InsertMessage(JsonConvert.SerializeObject(j), JsonConvert.SerializeObject(t.Result));

                                        }

                                    }
                                }
                                break;
                            case "9"://项目状态
                                HttpResponseMessage response2 = client.PostAsync(ConfigHelper.GetConfig().asset + "projectendresult", httpContent).Result;
                                if (response2.IsSuccessStatusCode)
                                {
                                    Task<string> t = response2.Content.ReadAsStringAsync();
                                    if (t != null)
                                    {
                                        result = t.Result;
                                        _logger.Info(result);
                                        JObject j1 = JObject.Parse(t.Result);
                                        if (j1["status"].ToString() == "True")
                                        {
                                            string data = j1["data"].ToString();
                                            try
                                            {
                                                data = DES.DecryptDES(data, ConfigHelper.GetConfig().desKey);
                                            }
                                            catch (Exception e)
                                            {
                                                _logger.Info("回调接口projectpublish，解密失败");
                                            }
                                            _logger.Debug("解密后：" + data);
                                            JObject jb = JObject.Parse(data);
                                            jb["projresult"] = 12;
                                            await BusinessRule.Warning.Waring.SaveProjectendresult(jb);

                                            string ver = await BusinessRule.Warning.Waring.InsertContract(jb);
                                            if (ver == "")
                                            {
                                                _logger.Debug("合同数据保存成功");
                                            }
                                            else
                                            { _logger.Debug("合同数据保存失败：" + ver); }
                                            string err = await BusinessRule.Warning.Waring.InsertMessage(JsonConvert.SerializeObject(j), JsonConvert.SerializeObject(t.Result));
                                        }

                                    }
                                }
                                break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }

    public class JobSchedulerWork
    {
        public static async void Work()
        {
            //调度器工厂
            ISchedulerFactory Work = new StdSchedulerFactory();
            //调度器
            IScheduler schedulers_work = await Work.GetScheduler();
            await schedulers_work.GetJobGroupNames();
            /*-------------计划任务代码实现------------------*/
            //创建任务
            IJobDetail job_Work = JobBuilder.Create<WorkJob>()
                .WithIdentity("TimeTriggerddd", "TimeGroupdd")
                .Build();
            //创建触发器 一分时被执行
             ITrigger trigger9 = TriggerBuilder.Create().WithCronSchedule("*/10 * * * * ?").WithIdentity("TimeTriggerddd", "TimeGroupdd").Build();
            //每隔多久执行一次  这个是每隔多久执行一遍
            //ITrigger trigger9 = TriggerBuilder.Create().WithIdentity("TimeTriggerddd", "TimeGroupdd").WithSimpleSchedule(t => t.WithIntervalInSeconds(1200).RepeatForever()).Build();
            //添加任务及触发器至调度器中
            await schedulers_work.ScheduleJob(job_Work, trigger9);
            /*-------------计划任务代码实现------------------*/
            //启动
            await schedulers_work.Start();
        }


    }
}
